/*
 *  $Id: FontInfoCollection.cs 1216 2010-11-26 17:35:07Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008-2009 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System.Collections.Generic;

using AgateLib.BitmapFont;

using Nereal.Serialization;

namespace Ragima.Languages {
    /// <summary>
    /// Информация о наборе шрифтов.
    /// </summary>
    [XmlRootName("fonts")]
    public sealed class FontInfoCollection {
        [Serialize, XmlName("ranges", "range")]
        private readonly List<CharacterRange> _ranges;
        [Serialize, XmlName("fonts", "font"), KeyName("id")]
        private readonly Dictionary<string, FontInfo> _fonts;

        public FontInfoCollection() {
            _ranges = new List<CharacterRange>();
            _fonts = new Dictionary<string, FontInfo>();
        }

        public IEnumerable<KeyValuePair<string, BitmapFontOptions>> GetFonts() {
            foreach (var info in _fonts) {
                var options = info.Value.GetOptions();
                foreach (var range in _ranges)
                    range.AddTo(options);
                yield return new KeyValuePair<string, BitmapFontOptions>(info.Key, options);
            }
        }

        public static FontInfoCollection Load(string filename) {
            return Serializer.Default.Deserialize<FontInfoCollection>(filename);
        }

        public struct CharacterRange {
            public const char NullChar = '\0';

            private char _start, _end;

            [XmlName("char")]
            public char StartChar {
                get { return _start; }
                set {
                    _start = value;
                    if (_end <= value)
                        _end = NullChar;
                }
            }

            // TODO : maybe member default value
            [XmlName("endChar"), DefaultValue(NullChar)]
            public char EndChar {
                get { return _end; }
                set {
                    if (value != NullChar && _start >= value) {
                        _start = value;
                        _end = NullChar;
                    } else
                        _end = value;
                }
            }

            private char RealEndChar {
                get { return _end != NullChar ? _end : _start; }
            }

            public void AddTo(BitmapFontOptions options) {
                options.AddRange(StartChar, RealEndChar);
            }
        }
    }
}
